import { getSelection, batchUpdateValue,fireExecute, sdp_language_sql_extra_info } from '/src/utils/index'
import { ElMessage, ElMessageBox } from "element-plus";
import { post } from "/src/api/index";
import { computed } from 'vue'
import { ref, unref, watch, onMounted } from 'vue'
import { sortObject } from '/src/utils/index'
import { errorMonitor } from 'events';

export function init(self) {
  const module = self.module.value
  self.title = ref('sql')
  self.extra_info_columns = sdp_language_sql_extra_info.filter(ele => ele.label!='==')

  self.custom = {
    columns : [
      {
        prop: 'id',
        hide: true,
      },
      {
        prop: 'workspace_name',
        order: 'asc',
        width: 150,
      },
      {
        prop: 'project_names',
        order: 'asc',
        width: 200,
      },
      {
        prop: 'table_name',
        order: 'asc',
        width: 150,
      },
      {
        prop: 'parameter_catalog_type',
        order: 'asc',
        width: 250,
      },
      {
        prop: 'parameter_catalog',
        order: 'asc',
        width: 110,
      },
      {
        prop: 'sort_no',
        order: 'asc',
        width: 100,
      },
      {
        prop: 'name',
        order: 'asc',
        width: 200,
      },
      {
        prop: 'java_type',
        width: 200,
      },
      {
        prop: 'remarks',
        width: 100,
      },
      {
        prop: 'parameter_is_like',
        width: 100,
      },
      {
        prop: 'parameter_sql_value',
        width: 100,
      },
      {
        prop: 'parameter_without_test',
        width: 100,
      },
      {
        prop: 'parameter_sql',
        width: 100,
      },
      {
        prop: 'parameter_nullable',
        width: 100,
      },
      {
        prop: 'parameter_sql_value_ignore',
        width: 100,
      },
      {
        prop: 'java_imports',
        width: 100,
      },
      {
        prop: 'java_return_type',
        width: 100,
      },
      {
        prop: 'is_interface',
        width: 100,
      },
      {
        prop: 'parameter_is_import_excel',
        width: 100,
      },
      {
        prop: 'parameter_is_export_excel',
        width: 100,
      },
      {
        prop: 'extra_info',
        width: 100,
      },
      ...self.extra_info_columns.map(ele => {
        return {
          ...ele,
          prop: 'extra_info_'+ele.prop,
          width: 100,
        }
      }),
      {

      }
    ],

    editColumns : [
      {
        prop: 'id',
        hide: true,
      },
      {
        prop: 'is_disable',
        hide: true,
      },
      {
        prop: 'parameter_mode',
        hide: true,
      },
      {
        prop: 'workspace_name',
        label: '工作区',
        list_remote: {
          module: 'sdp_workspace', method:'list',
          query: {},
          sortInfo: ['name'],
          mapInfo: {label:'name', value:'name'}
        },
        type: 'select',
        required: true,
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage, editDialogInfo} = param
          editDialogInfo = unref(editDialogInfo)
          if(form.workspace_name) {
            post('sdp_workspace_config', 'list', {
              workspace_name: form.workspace_name,
            })
            .then(data => {
              editDialogInfo.configs = data
            })
          }

          get_remote_list({...param, columns,
            prop: '_project_names', query: {workspace_name: form[column.prop]}})
          get_remote_list({...param, columns,
            prop: 'table_name', query: {workspace_name: form[column.prop]}})
          .then(param => {
            const { data } = param
            if (data && data.length) {
              let column = columns.find(ele => ele.prop == 'table_name')
              column.list.forEach( ele => {
                if (ele.data) {
                  if (ele.data.alias_name && ele.data.alias_name != ele.data.name) {
                    ele.label = ele.data.name + ' as '+ele.data.alias_name
                  }
                  let remark = ele.data.remark
                  if (remark) {
                    remark += ''
                    remark = remark.split('\n')[0].split('\r')[0].trim()
                    if (remark.length > 15) {
                      remark = remark.substring(0, 15)+'...'
                    }
                    ele.label += ' ('+remark+')'
                  }
                }
              })
              // if (form.table_name && !data.find(ele => ele.name == form.table_name)) {
              //   form.table_name = ''
              // }
            }
          })
        },
      },
      {
        prop: '_project_names',
        placeholder: '项目列表',
        label: '项目列表',
        type: 'select',
        disabled: false,
        multiple: true,
        list_remote: {
          module: 'sdp_project', method:'list',
          mode: 'dynamic',
          query: {},
          sortInfo: ['workspace_name', 'name'],
          mapInfo: {label:'name', value:'name'}
        },
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          if(mode.indexOf('init') < 0) {
            form.project_names = form[column.prop].join(',')
            form.extra_info_common_project__s = (form[column.prop] || []).map(ele => ({label: ele, value:ele}))
            if(!form.extra_info_common_project__s || !form.extra_info_common_project__s.length) {
              form.extra_info_common_project__s = [...columns.find(ele => ele.prop == '_project_names').list]
            }
          }
        }
      },
      {
        prop: 'project_names',
        placeholder: '项目列表',
        hide: true,
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          // form.extra_info_common_project__s = (form._project_names || []).map(ele => ({label: ele, value:ele}))
        }
      },
      {
        prop: 'table_name',
        width: 150,
        placeholder: '表',
        type: 'select',
        list_remote: {
          module: 'sdp_workspace', method:'get_table_list',
          mode: 'dynamic',
          query: {},
          sortInfo: [],
          mapInfo: {label:'name', value:'alias_name'},
          cbBefore: ({data, column}) => {
            console.log('cbBefore', data)
            data.map(ele => {
              if(!ele.alias_name) {
                ele.alias_name = ele.name
              }
            })
          }
        },
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage, editDialogInfo} = param
          editDialogInfo = unref(editDialogInfo)
          console.log('table_name change', form.workspace_name, form.table_name, param)
          if(form.workspace_name && form.table_name) {
            return post('sdp_workspace', 'get_column_list', {
              workspace_name: form.workspace_name,
              table_name: form.table_name,
              // parameter_sql: r.parameter_sql
            })
            .then(data => {
              console.log('table_name change data', data)
              if(data && data.length && data[0].extra_info) {
                let extraInfo = JSON.parse(data[0].extra_info)
                if(extraInfo.tableInfo) {
                  editDialogInfo.table_info = {...editDialogInfo.table_info, ...extraInfo.tableInfo}
                }
                console.log('table_name change extraInfo', extraInfo)
                console.log('table_name change table_info', editDialogInfo.table_info)
                for(let name in  editDialogInfo.table_info) {
                  console.log('---- table info:'+name)
                  let table_info = editDialogInfo.table_info[name]
                  for(let c in table_info) {
                    c = parseInt(c)
                    let _c = table_info[c]
                    console.log('table info', (c+1)+','+_c.actualColumnName+','+_c.jdbcTypeName+','+_c.remarks.split('\n')[0])
                  }
                }
              }
            })
          }
        }
      },
      {
        prop: 'parameter_catalog',
        width: 150,
        type: 'select',
        list: [
          { label: 'SQL', value: 'sql' },
          { label: 'SQL参数-sql.param', value: 'sql.param' },
          { label: 'SQL结果扩展属性-sql.reponse', value: 'sql.response' },
          { label: '自定义方法-api.facade', value: 'api.facade' },
          { label: '内置方法请求扩展属性-api.request', value: 'api.request' },
          { label: '内置方法结果扩展属性-api.response', value: 'api.response' },
        ],
        onchange: param => {
          let {mode, form, form_ori, column, columns, get_remote_list, set_query_storage} = param
          if (!form) {
            //TODO 为什么会调用到这里？？？
            console.error('param', param)
            return;
          }
          if(form[column.prop] == 'sql.param'
            || form[column.prop] == 'sql.param'
          ) {
            columns.find(ele => ele.prop == '_project_names').disabled = true;
          } else {
            columns.find(ele => ele.prop == '_project_names').disabled = false;
          }
          let map = {
            sql: [
              '_project_names',
              'project_names',
              'parameter_sql',
              'is_interface',
              'is_nolist',
              'is_formdata',
              'is_update',
              'is_frontend_list',
              'url',
              'java_return_type',
              'java_imports',
              'extra_info_common_project_',
              // 'parameter_sql_issimple',
            ],
            'sql.param': [
              '_project_names',
              'project_names',
              'name',
              'java_type',
              'is_collection',
              'is_dollar',
              'sql_replace_line',
              'parameter_nullable',
              'parameter_is_like',
              'parameter_sql_value',
              'parameter_sql_value_ignore',
              'parameter_without_test',
              'java_imports',
              'request_json_name',
            ],
            'sql.response': [
              '_project_names',
              'project_names',
              'name',
              'java_type',
              'java_imports',
              'response_json_name',
              'response_default_value',
            ],
            'api.facade': [
              '_project_names',
              'project_names',
              'name',
              'java_type',
              'java_imports',
              'parameter_is_import_excel',
              'parameter_is_export_excel',
              'java_return_type',
              'request_extra_param',
              'request_extra_param_simple',
              'request_extra_param_web',
              'url',
            ],
            'api.response': [
              '_project_names',
              'project_names',
              'name',
              'java_type',
              'java_imports',
              'response_json_name',
            ],
            'api.request': [
              '_project_names',
              'project_names',
              'name',
              'java_type',
              'java_imports',
              'parameter_nullable',
              'request_json_name',
            ],
          }
          let list = map[form[column.prop]];
          if(!list) {
            console.error('非法类型：', column)
            console.error('非法类型：', column.prop, column)
            console.error('非法类型：', form)
            console.error('非法类型：', form[column.prop])
            return;
          }
          unref(self.editColumns).forEach(ele => {
            if (ele.prop == 'id'
              || ele.prop == 'workspace_name'
              || ele.prop == 'project_names'
              || ele.prop == 'table_name'
              || ele.prop == 'parameter_catalog'
              || ele.prop == 'parameter_catalog_type'
              || ele.prop == 'extra_info'
              || ele.prop == 'remarks'
              || ele.prop == 'remark'
              || ele.prop == 'sort_no'
            ) {
              return;
            }
            let p = ele.prop
            let extraP = 'extra_info_'+p
            if (self.extra_info_columns.find(e => e.prop == extraP)) {
              p = extraP
            }
            let valid = list.find(e => e == p) || list.find(e => 'extra_info_' + e == p)
            if (valid) {
              ele.hide = false
            } else {
              ele.hide = true
            }
          })

        }
      },
      {
        prop: 'parameter_catalog_type',
        width: 150,
        disabled: false,
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          if(mode.indexOf('init') < 0) {
            form[column.prop] = form[column.prop].replace(/([A-Z])/g,"_$1").toLowerCase();
          }
        }
      },
      {
        prop: 'name',
        width: 150,
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          if(mode.indexOf('init') < 0) {
            form[column.prop] = form[column.prop].replace(/([A-Z])/g,"_$1").toLowerCase();
          }
        }
      },
      {

      },
      {
        prop: 'parameter_is_like',
        type: 'switch',
      },
      {

      },
      {
        prop: 'parameter_without_test',
        type: 'switch',
      },
      {
        prop: 'parameter_sql',
        type: 'parameter_sql',
        rows: 8,
        oninit: param => {
            const {mode, form, column, columns, get_remote_list, dialogInfo} = param
            form.parameter_sql_tip = '常用单独一行注释对应的指令（针对接口）:\n'
            +'  -- ignore dup column 【忽略重复的字段错误】\n'
            +'  -- name: xx 【设置接口名称】\n'
            +'  -- table: xx 【对应的project中的表别名】未设置别名时为表名\n'
            +'  -- remarks: xx 【设置接口注释】\n'
            +'  -- return: xx 【设置返回结果类型】与no list不可同时设置\n'
            +'  -- no list 【不返回List类型结果】与return不可同时设置\n'
            +'  -- form data【接口为FormData格式】\n'
            +'  -- import:【导入java类】\n'
            +'  -- interface 【设置为纯接口类型】无where条件的select默认为interface\n'
            +'  -- not interface 【设置为非纯接口类型】\n'
            +'\n'
            +'单独一行注释对应字段的指令（针对字段）:\n'
            +'  -- (column_name) xxx 【参加下面说明】\n'
            +'\n'
            +'自动参数生成有两种方式：\n'
            +'1)以小写and 开始的行\n'
            +'2)可在语句中使用\'#{xxYy}\'方式定义参数，同时设置参数名称\n'
            +'\n'
            +'常用字段或where条件语句所在行，同行内注释对应的指令（针对参数或字段）\n'
            +'  -- type:xx 【设置字段类型】基础类型或List<、Map<、Set<格式可省略type:前缀\n'
            +'  -- request【为请求参数】\n'
            +'  -- no test【mybatis xml中不生成<if test...条件】自动设置为请求参数\n'
            +'  -- not null【禁止为空】自动设置为请求参数\n'
            +'  -- like【为like请求参数】自动设置为请求参数\n'
            +'  -- MultipartFile类型时接口自动设置为form data\n'
            +'  -- import:【导入java类】\n'
        },
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage, editDialogInfo} = param
          editDialogInfo = unref(editDialogInfo)
          console.log('param', param, editDialogInfo)
          if(!form.parameter_sql || !form.workspace_name) {
            return
          }

          let promiseList = []
          promiseList.push(
          )
          unref(editDialogInfo.columns).find(col => col.prop == 'parameter_sql').errorMsg = ''
          editDialogInfo.params = []
          promiseList.push(
            post('sdp_workspace', 'get_column_list', {
              workspace_name: form.workspace_name,
              table_name: form.table_name,
              parameter_sql: form.parameter_sql
            })
            .then(data => {
              if(data && data.length && data[0].extra_info) {
                let extraInfo = JSON.parse(data[0].extra_info)
                if(extraInfo.explainInfo && extraInfo.explainInfo.Extra && extraInfo.explainInfo.Extra == 'Impossible WHERE') {
                  unref(editDialogInfo.columns).find(col => col.prop == 'parameter_sql').errorMsg = 'Where条件永远为假！'
                }
                editDialogInfo.sql_info = extraInfo
                if(extraInfo.tableInfo) {
                  editDialogInfo.table_info = {...editDialogInfo.table_info, ...extraInfo.tableInfo}
                }
                console.log('get_column_list sql_info', extraInfo)
                console.log('get_column_list table_info', extraInfo.tableInfo)
              }
            })
          )
          Promise.all(promiseList).then( () => {
            
          })

          
        }
      },
      {
        prop: 'parameter_nullable',
        type: 'switch',
      },
      {
        prop: 'parameter_sql_value_ignore',
        type: 'switch',
      },
      {
        prop: 'extra_info_common_project_',
        label: '表通用扩展属性',
        type: 'extra_info_common_project_',
        buttons: [
          {
            label: '删除',
            onclick: param => {
              let {form} = param
              if(form.extra_info_common_project__k) {
                if(form.extra_info_common_project__p) {
                  let extra_info = JSON.parse(form.extra_info||'{}')
                  delete extra_info['_project_'+form.extra_info_common_project__p+';'+form.extra_info_common_project__k]
                  form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
                } else {
                  let extra_info = JSON.parse(form.extra_info||'{}')
                  delete extra_info[form.extra_info_common_project__k]
                  form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
                }
              } else if(form.extra_info_common_project__p) {
                let extra_info = JSON.parse(form.extra_info||'{}')
                for(let p in extra_info) {
                  if(p.indexOf('_project_'+form.extra_info_common_project__p+';') == 0) {
                    if(form.extra_info_common_project__v == extra_info[p]) {
                      delete extra_info[p]
                    } else if(!form.extra_info_common_project__v && form.extra_info_common_project__v !== '0'){
                      delete extra_info[p]
                    }
                  }
                }
                form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
              }
            }
          },
          {
            label: '新增',
            onclick: param => {
              let {form} = param
              if(form.extra_info_common_project__k) {
                if(form.extra_info_common_project__p) {
                  let extra_info = JSON.parse(form.extra_info||'{}')
                  extra_info['_project_'+form.extra_info_common_project__p+';'+form.extra_info_common_project__k] = form.extra_info_common_project__v
                  form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
                } else {
                  let extra_info = JSON.parse(form.extra_info||'{}')
                  extra_info[form.extra_info_common_project__k] = form.extra_info_common_project__v
                  form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
                }
              }
            }
          },
        ],
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          if (mode.indexOf('init') < 0) {
            if(form.extra_info_common_project__v !== undefined && form.extra_info_common_project__v !== null) {
              if(form.extra_info_common_project__p && form.extra_info_common_project__k) {
                let extra_info = JSON.parse(form.extra_info||'{}')
                extra_info['_project_'+form.extra_info_common_project__p+';'+form.extra_info_common_project__k] = form.extra_info_common_project__v
                
                form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
              } else if (form.extra_info_common_project__k) {
                let extra_info = JSON.parse(form.extra_info||'{}')
                extra_info[form.extra_info_common_project__k] = form.extra_info_common_project__v
                
                form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
              }
            } else {
              if(form.extra_info_common_project__k) {
                let c = self.configs['extra_info_sql_'+form.extra_info_common_project__k]
                if(c && c.extra_info) {
                  let extra_info = JSON.parse(c.extra_info)
                  if(extra_info.default_value) {
                    form.extra_info_common_project__v = extra_info.default_value
                    column.onchange(param)
                  }
                }
              }
            }
          }
        },
      },
      {
        prop: 'extra_info',
        type: 'textarea',
        rows: 5,
        onclick: param => {
          let txt = unref(unref(self).editDialogInfo).form.extra_info
          let target = param.srcElement
          if('selectionStart' in target) {
            let leftStr = txt.substr(0, target.selectionStart)
            let line = leftStr.split('\n').length-1
            let array =  txt.split('\n')
            let leftKey = array[line].split(':')[0]
            leftKey = JSON.parse(leftKey)
            if(leftKey) {
              let extra_info = JSON.parse(unref(unref(self).editDialogInfo).form.extra_info)
              if(leftKey.indexOf('_project_') == 0) {
                unref(unref(self).editDialogInfo).form.extra_info_common_project__p = leftKey.substring('_project_'.length).split(';')[0]
                unref(unref(self).editDialogInfo).form.extra_info_common_project__k = leftKey.substring('_project_'.length).split(';')[1]
                unref(unref(self).editDialogInfo).form.extra_info_common_project__v = extra_info[leftKey]
              } else {
                unref(unref(self).editDialogInfo).form.extra_info_common_project__p = ''
                unref(unref(self).editDialogInfo).form.extra_info_common_project__k = leftKey
                unref(unref(self).editDialogInfo).form.extra_info_common_project__v = extra_info[leftKey]
              }
            }
          }
        },
      },
      {
        prop: 'java_return_type',
      },
      {
        prop: 'remarks',
      },
      {
        prop: 'java_imports',
        type: 'textarea',
      },
      {
        prop: 'is_interface',
        type: 'switch',
      },
      // {
      //   prop: 'extra_info',
      //   type: 'textarea',
      // },
      ...self.extra_info_columns.map(ele => {
        let onchange = param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          let extra_info
          if (form.extra_info) {
            extra_info = JSON.parse(form.extra_info)
          } else {
            extra_info = {}
          }
          let prop = column.prop.substring('extra_info_'.length)
          if (form[column.prop]) {
            extra_info[prop] = form[column.prop]
          } else {
            delete extra_info[prop]
          }
          form.extra_info = JSON.stringify(extra_info, null, 2)
        }
  
        if (ele.prop.indexOf('is_') >= 0) {
          return {
            ...ele,
            prop: 'extra_info_'+ele.prop,
            type: 'switch',
            onchange,
          }
        }
        return {
          ...ele,
          prop: 'extra_info_'+ele.prop,
          onchange,
        }
      }),
      {

      },
      {
        prop: 'parameter_is_import_excel',
        type: 'switch',
      },
      {
        prop: 'parameter_is_export_excel',
        type: 'switch',
      },
      {
        prop: 'sort_no',
      }
    ],

    queryColumns : [
      {
        prop: 'workspace_name',
        fixed: true,
        list_remote: {
          module: 'sdp_workspace', method:'list',
          query: {},
          sortInfo: ['name'],
          mapInfo: {label:'name', value:'name'},
        },
        type: 'select',
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          get_remote_list({...param, columns,
            prop: 'table_name_like', query: {workspace_name: form[column.prop]}})
          .then(param => {
            const { data } = param
            if (data && data.length) {
              let column = columns.find(ele => ele.prop == 'table_name_like')
              column.list.forEach( ele => {
                if (ele.data) {
                  if (ele.data.alias_name) {
                    ele.label += ' as '+ele.data.alias_name
                    ele.value = ele.data.alias_name
                    // console.log('e le', ele.value, ele)
                  }
                  let remark = ele.data.remark
                  if (remark) {
                    remark += ''
                    remark = remark.split('\n')[0].split('\r')[0].trim()
                    if (remark.length > 15) {
                      remark = remark.substring(0, 15)+'...'
                    }
                    ele.label += ' ('+remark+')'
                  }
                }
              })
              column.list = [...column.list]
              // if (form.table_name_like && !data.find(ele => ele.value == form.table_name_like)) {
              //   form.table_name_like = ''
              // }
            }
          })
        },
      },
      {
        prop: 'table_name_like',
        label: '表',
        width: 150,
        type: 'select',
        list_remote: {
          module: 'sdp_workspace', method:'get_table_list',
          mode: 'dynamic',
          query: {},
          sortInfo: [],
          mapInfo: {label:'name', value:'name'}
        },
      },
      {
        prop: 'parameter_catalog_type_like',
        label: '方法名',
        width: '150px',
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          if(mode.indexOf('init') < 0) {
            form[column.prop] = form[column.prop].replace(/([A-Z])/g,"_$1").toLowerCase();
          }
        }
      },
      {
        prop: 'name_like',
        label: '名称',
        width: '150px',
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          if(mode.indexOf('init') < 0) {
            form[column.prop] = form[column.prop].replace(/([A-Z])/g,"_$1").toLowerCase();
          }
        }
      },
      {
        prop: 'parameter_sql_like',
        label: 'SQL',
        width: '150px',
      },
      {
        prop: 'extra_info_like',
        label: '扩展属性',
        width: '150px',
      },
    ],

    buttons: [
      {
        prop: 'batchEdit',
        label: '批量编辑',
        loading: false,
        onclick: (param) => {
          let {batchEditDialogInfo : dialogInfo, selectRows} = self
          dialogInfo = unref(dialogInfo)
          selectRows = unref(selectRows)
          if (!selectRows || selectRows.length == 0) {
            ElMessage.error(`请选择至少一条记录后再操作`);
            return;
          }

          selectRows = unref(selectRows)
          let item = selectRows[0]
          dialogInfo.form = {...item}
          dialogInfo.form_ori = {...item}
          dialogInfo.show({...param, dialogInfo})
        }
      },
      {
        prop: 'fireExecute',
        label: '生成文件',
        loading: false,
        type: 'success',
        onclick: (param) => {
          fireExecute({param, self})
        }
      },
      {
        prop: 'fireExecuteAi',
        label: '生成文件(ai)',
        loading: false,
        onclick: (param) => {
          fireExecute({param, self, isAi:true})
        }
      },
    ],

    remoteConfig : {
    },

    onInit: () => {

      self.toJavaType = (col) => {
        if(col.jdbcTypeName == 'BIGINT') {

        }
      }
      self.getLastToken = (line) => {
        try {
            let bytes = line;
            let len = bytes.length;
            let pos = len - 1;
            let destBytes = '';
            let destPos = 0;
            // debugger
            while (pos >= 0) {
                do {
                    try {
                        let b = bytes.charAt(pos);
                        if(b == '`' || b == ',') {
                            continue;
                        }
                        if(b >= '0' && b <= '9'
                                || b >= 'a' && b <= 'z'
                                || b >= 'A' && b <= 'Z'
                                || b == '`'
                                || b == '_'
                                || b == '$'
                        ) {
                            destBytes += b;
                            destPos++;
                        } else {
                            pos = 0;
                            break;
                        }
                    }catch (ex) {
                        console.error('ex', ex)
                    }
                }while(false);
                pos--;
            }
            if(destPos > 0) {
                let b2 = '';
                for(let i = 0; i < destPos; i++) {
                    b2 += destBytes.charAt(destPos - i - 1);
                }
                console.log('getLastToken', b2, line)
                return b2;
            }
        } catch (e) {
            throw e
        }
        return null;
      }

      self.isJavaType = (s) => {
        if(!s) {
            return null;
        }
        let types = ["boolean", "Boolean", "int", "long", "Integer", "Long", "BigDecimal", "double", "float", "Double", "Float", "List<>", "Map<>", "Set<>"]
        return types.find(ele => ele == s)
      }

      self.handleSearch_ori = self.handleSearch
      console.log('self.editDialogInfo', self.editDialogInfo, self)
      let editDialogInfo = unref(self.editDialogInfo)
      editDialogInfo.show_ori = unref(self.editDialogInfo).show
      editDialogInfo.analyse_sql = (param) => {

      }
      editDialogInfo.show = (param) => {
        const {dialogInfo, query, title} = param
        console.log('dialogInfo', title, query, dialogInfo, param)

        editDialogInfo.fieldsInfoMap = {}
        editDialogInfo.sql_params = []
        editDialogInfo.sql_param_map = {}
        editDialogInfo.configs = []
        editDialogInfo.table_info = {}
        editDialogInfo.sql_info = {}
        unref(editDialogInfo.columns).map(ele => {
          delete ele.errorMsg
        })

        console.log('form', editDialogInfo.form, editDialogInfo, editDialogInfo.title)

        let promiseList = []
        if(title == '编辑') {
          let selectRows = unref(self.selectRows)
          console.log('selectRows', selectRows)
          if(selectRows && selectRows.length) {
            let r = selectRows[0]
            
            if(r.workspace_name) {
              promiseList.push(
                post('sdp_workspace_config', 'list', {
                  workspace_name: r.workspace_name,
                })
                .then(data => {
                  editDialogInfo.configs = data
                })
              )
            }
          }
        }

        Promise.all(promiseList)
        .finally(() => {
          return unref(self.editDialogInfo).show_ori(param)
        })
  
      }
      self.handleSearch = (param) => {

        let projects, configs, extra_info_common_project__ks
        return post('sdp_project', 'list', {
          workspace_name:unref(self.query).workspace_name,
          query_options: { order_by: [ { name: 'asc', } ] },
        })
        .then(data => {
          projects = data
          return post('sdp_workspace_config', 'list', {
            workspace_name:unref(self.query).workspace_name,
            query_options: { order_by: [ { name: 'asc', } ] },
          })
        })
        .then(data => {
          configs = data
          self.configs = {}
          data.map(ele => {
            self.configs[ele.name] = ele;
            if(ele.extra_info) {
              ele.extra_info_json = JSON.parse(ele.extra_info)
            }
            if(ele.name.indexOf('extra_info_sqlparam_') == 0) {
              let n = ele.name
              if(n == 'extra_info_sqlparam_is_nullable') {
                n = 'nullable'
              } else if (n == 'extra_info_sqlparam_is_without_test') {
                n = 'without_test'
              } else if (n == 'extra_info_sqlparam_is_sql_value_ignore') {
                n = 'sql_value_ignore'
              } else {
                n = n.substring('extra_info_sqlparam_'.length)
              }
              let c = unref(self.columns).find(e => e.prop == ('parameter_' + n))
              if(c) {
                c.hide = true
                c.prop = '__'+c.prop
              }
              c = unref(self.editColumns).find(e => e.prop == 'parameter_' + n)
              if(c) {
                c.hide = true
                c.prop = '__'+c.prop
              }
            }
          })
          extra_info_common_project__ks = configs.filter(ele => ele.name.indexOf('extra_info_sql_') == 0).map(ele => ({label: ele.value, value: ele.name.substring('extra_info_sql_'.length)}))
          return self.handleSearch_ori(param)
        })
        .then( data => {
          unref(self.tableData).forEach( ele => {
            if(ele.project_names) {
              ele._project_names = ele.project_names.split(',')
              ele.extra_info_common_project__s = ele._project_names.map(ele => ({label: ele, value: ele}))
            } else {
              ele.extra_info_common_project__s = projects.map(ele => ({label:ele.name, value: ele.name}))
            }
            ele.extra_info_common_project__ks = extra_info_common_project__ks
            if (ele.extra_info) {
              let j = JSON.parse(ele.extra_info)
              for(let p in j) {
                ele['extra_info_'+p] = j[p]
              }
              ele.extra_info = JSON.stringify(j, null, 2)
            }
          })
          return data;
        })
      }

      let dialogInfo = unref(self.editDialogInfo)

      dialogInfo.buttons = [...(dialogInfo.buttons || []), {
        prop: 'clone',
        label: 'Clone',
        loading: false,
        hide: computed(() => unref(dialogInfo.form).parameter_catalog != 'sql'),
        onclick: (param) => {
          let form = unref(param.form)
          let form_ori = unref(param.form_ori)
          if(form.workspace_name == form_ori.workspace_name
              && form.table_name == form_ori.table_name
              && form.parameter_catalog_type == form_ori.parameter_catalog_type) {
            ElMessage.error(`至少修改修改workspace_name,table_name,parameter_catalog_type中的一项`);
            return;
          }
          post('sdp_sql', 'list', {workspace_name:form_ori.workspace_name, table_name: form_ori.table_name, parameter_catalog_type: form_ori.parameter_catalog_type})
          .then(data => {
            for(let item in data) {
              item = {...data[item], disable_auto_param: 1}
              delete item.id
              if(item.parameter_catalog == 'sql') {
                item = {...form, disable_auto_param: 1}
                delete item.id
                post('sdp_sql', 'add', item)
              } else {
                item.workspace_name = form.workspace_name
                item.table_name = form.table_name
                item.parameter_catalog_type = form.parameter_catalog_type
                post('sdp_sql', 'add', item)
              }
            }
            dialogInfo.visible = false;
          })
        }
      }]
      dialogInfo.onconfirm_ori = dialogInfo.onconfirm
      dialogInfo.onconfirm = (param) => {
        let tableData = [...unref(self.tableData)]
        if (unref(dialogInfo.title) == '编辑') {
          if((unref(dialogInfo.form).table_name != unref(dialogInfo.form_ori).table_name
                || unref(dialogInfo.form).workspace_name != unref(dialogInfo.form_ori).workspace_name)
              && (unref(dialogInfo.form).parameter_catalog == 'sql.param' || unref(dialogInfo.form_ori).parameter_catalog == 'sql.param')) {
            ElMessage.error(`禁止直接修改sql.param条目的table_name或workspace_name`);
            return;
          }

          let form = unref(dialogInfo.form)
          let form_ori = unref(dialogInfo.form_ori)
          if((unref(dialogInfo.form).table_name != unref(dialogInfo.form_ori).table_name
                || unref(dialogInfo.form).workspace_name != unref(dialogInfo.form_ori).workspace_name)
              && (unref(dialogInfo.form).parameter_catalog == 'sql' && unref(dialogInfo.form_ori).parameter_catalog == 'sql')) {
            post('sdp_sql', 'list', {workspace_name:form_ori.workspace_name, table_name: form_ori.table_name, parameter_catalog_type: form_ori.parameter_catalog_type})
            .then(data => {
              for(let item in data) {
                item = {...data[item]}
                if(item.id == form_ori.id) {
                  continue;
                }
                item.workspace_name = form.workspace_name
                item.table_name = form.table_name
                item.parameter_catalog_type = form.parameter_catalog_type
                post('sdp_sql', 'update', item)
              }
            })
            // ElMessage.error(`批量修改`);
            // return;
          }
        }

        return dialogInfo.onconfirm_ori(param)
        .then( data => {
          if (unref(dialogInfo.title) == '编辑' && unref(dialogInfo.form).parameter_catalog == 'sql') {
          }
        })
      }
    },
    onMounted: (param) => {
      console.log('onMounted', param, unref(self.name))
    }
  }
}

